//index.js
//获取应用实例
const app = getApp();
const util = require('../../../utils/util.js')
Page({
  data: {
    items0: [], //全部订单
    pageNum0: 0,
    has0: true,
    loading0: false,

    items1: [], // 完成订单
    pageNum1: 0,
    has1: true,
    loading1: false,

    items2: [], // 失效订单
    pageNum2: 0,  
    has2: true,
    loading2: false,

    limit: 10,

    swiperViewHeight: 0,
    currentTab: 0,
    inputShowed: false,
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1200,
  },
  swiperchange: function (e) {
    //FIXME: 当前页码
    //console.log(e.detail.current)
  },

  onLoad: function () {
    //调用应用实例的方法获取全局数据
    // this.setData({currentTab: 2})
    
    // wx.pageScrollTo({
    //   scrollTop: 0
    // })
  },
  get0: function () {
    // 全部订单
    var that = this;
    if (that.data.loading1) return

    that.data.loading0 = true;
    var pageNum0 = that.data.pageNum0;
    var limit = that.data.limit;
    //playingList
    wx.request({
      url: app.globalData.url + '/appletSupplierRob/waitingRobList',
      method: 'POST',
      data: {
        pageNum: ++pageNum0,
        pageSize: limit
      },
      header: {
        'Accept': 'application/json',
        consumerId: app.globalData.userInfo.consumerId
      },
      success: function (res) {
        console.log(0);
        const items0 = that.data.items0.concat(res.data.data.rows && res.data.data.rows.map(i=> {
          const diffTime = Math.floor((new Date(i.biddingEndtime) - new Date())); //计时器
          return {
            ...i,
            status: that.typeConvert(i.payFlag, 'color'),
            statusName: that.typeConvert(i.payFlag, 'name'),
            disabled: true,
            diffTime
          }
        }));
        that.setData({
          has0: pageNum0 <= Math.ceil(res.data.data.total / 10),
          items0,
          pageNum0: pageNum0
        })
        if (that.data.currentTab == 0) {
          that.setSwiperHeight();
        }
        that.data.loading0 = false;
      }
    })
  },
  get1: function () {
    // 完成订单
    var that = this;
    if (that.data.loading1) return

    that.data.loading1 = true;
    var pageNum1 = that.data.pageNum1;
    var limit = that.data.limit;
    //playingList
    wx.request({
      // url: app.globalData.url + '/appletSupplierRob/waitingRobList',
      url: app.globalData.url + '/appletSupplierRob/biddingList',
      method: 'POST',
      data: {
        pageNum: ++pageNum1,
        pageSize: limit
      },
      header: {
        'Accept': 'application/json',
        'ConsumerId': app.globalData.userInfo.consumerId
      },
      success: function (res) {
        console.log(1);
        const items1 = that.data.items1.concat(res.data.data.rows && res.data.data.rows.map(i=> {
          const diffTime = Math.floor((new Date(i.biddingEndtime) - new Date())); //计时器
          return {
            ...i,
            status: that.typeConvert(i.payFlag, 'color'),
            statusName: that.typeConvert(i.payFlag, 'name'),
            disabled: true,
            diffTime
          }
        }));
        that.setData({
          has1: pageNum1 <= Math.ceil(res.data.data.total / 10),
          items1,
          pageNum1: pageNum1
        })
        if (that.data.currentTab == 1) {
          that.setSwiperHeight();
        }
        that.data.loading1 = false;
      }
    })
  },
  get2: function () {
    // 失效订单
    var that = this;
    if (that.data.loading2) return
    that.data.loading2 = true;
    var pageNum2 = that.data.pageNum2;
    var limit = that.data.limit;
    wx.request({
      // url: app.globalData.url + '/appletSupplierRob/waitingRobList',
      url: app.globalData.url + '/appletSupplierRob/standbyTicket/5',
      method: 'POST',
      header:{
        consumerId: app.globalData.userInfo.consumerId
      },
      data: {
        pageNum: ++pageNum2,
        pageSize: limit
      },
      success: function (res) {
        console.log(2);
        const items2 = that.data.items2.concat(res.data.data.rows && res.data.data.rows.map(i=> {
          return {
            ...i,
            status: that.typeConvert(i.payFlag, 'color'),
            statusName: that.typeConvert(i.payFlag, 'name'),
            diffTime: 0
          }
        }));
        that.setData({
          has2: pageNum2 <= Math.ceil(res.data.data.total / 10),
          items2,
          pageNum2: pageNum2
        })
        if (that.data.currentTab == 2) {
          that.setSwiperHeight();
        }
        that.data.loading2 = false;
      }
    })
  },
  onReachBottom: function () {
    if (this.data.currentTab == 0 && this.data.has0)
      this.get0();
    else if (this.data.currentTab == 1 && this.data.has1)
      this.get1();
      else if (this.data.currentTab == 2 && this.data.has2)
      this.get2();
  },
  setSwiperHeight: function () {
    var query = wx.createSelectorQuery();
    //选择id
    var that = this;
    var px1 = 208 / 750 * wx.getSystemInfoSync().windowWidth;
    var px2 = 376 / 750 * wx.getSystemInfoSync().windowWidth;
    query.selectAll('.swiperH').boundingClientRect(function (rect) {

      var itemsLength = 0;
      if (that.data.currentTab == 0){
        itemsLength = (278 + 18)*that.data.items0.length + 18 + 100;
      }else if(that.data.currentTab == 1){
        itemsLength = (278 + 18)*that.data.items1.length + 18;
      }else if(that.data.currentTab == 2){
        itemsLength = (220)*that.data.items2.length+ 18;
      }
      that.setData({
        swiperViewHeight: itemsLength
      })
    }).exec();
  },
  //点击切换
  onChange: function (e) {
    var that = this;
    console.log(e.detail.index);
    if (this.data.currentTab === e.detail.index) {
      return false;
    } else {
      this.initGet(e.detail.index)
      that.setData({
        currentTab: e.detail.index
      })
    }
  },
  onShow: function () {
    this.setData({
      items0: [], //全部订单
      pageNum0: 0,
      has0: true,
      loading0: false,

      items1: [], // 完成订单
      pageNum1: 0,
      has1: true,
      loading1: false,

      items2: [], // 失效订单
      pageNum2: 0,  
      has2: true,
      loading2: false,
    })
    this.get0();
    this.get1();
    this.get2();
  },
  typeConvert: function(val, name){
    let status = {
      NO_PAY: '未支付',
      PAY_ING: '支付中',
      PAY_FAIL: '支付失败',
      PAY_SUCCESS: '已支付',
      SENDING: '退款发送中',
      PROCESSING: '退款中',
      SUCCESS: '退款成功',
      CLOSED: '退款关闭',
      ABNORMAL: '退款异常',
    }
    let color = {
      NO_PAY: 'color1',
      PAY_ING: 'color1',
      PAY_FAIL: 'color0',
      PAY_SUCCESS: 'color2',
      SENDING: 'color1',
      PROCESSING: 'color1',
      SUCCESS: 'color2',
      CLOSED: 'color1',
      ABNORMAL: 'color0',
    }
    if (name == 'name') {
      return status[val]
    } else if (name == 'color') {
      return color[val]
    }
  },
  submit(e) {
    console.log(e.currentTarget);
    const item = e.currentTarget.dataset.item
    if(item.payFlag == 'NO_PAY' || item.payFlag == 'PAY_ING') {
      const paramsStr = JSON.stringify({
        ...item,
        cinemaName: item.movieInfo.name,//电影院名
        cinemaId: item.cinemaId,//电影院ID
        hall: item.movieInfo.hallName,//大厅
        movieName: item.movieInfo.name,//电影名
        movieImg:item.movieInfo.pic,//海报
        movieId:item.movieInfo.movieId,  // 电影ID
        grade: item.movieInfo.grade, // 评分
        duration: item.movieInfo.duration, // 播放时长
        time: item.movieInfo.showTime,//时间
        price: item.ticketUnitPrice,//票价
        seat: item.seatNo && item.seatNo.split(';'),//座位 座位名字集合
        seatIds: item.seatId && item.seatId.split(';'), // 座位ids
        seatNo: item.seatNo && item.seatNo.split(';'), // 座位名称
        showId: item.showId, // 场次Id
        ticketNum: item.seatNo.split(';').length,  // 选中的座位数
        ticketOriginalPrice: item.ticketOriginalPrice, // 原本票价
        ticketUnitPrice: item.ticketUnitPrice,  // 特惠票价
        totalPrice: item.ticketTotalPrice,//票价
        consumerId: app.globalData.userInfo.consumerId,
        orderId: item.orderId
      });
      wx.navigateTo({
        url: `/pages/subPages/buy-ticket/buy-ticket?paramsStr=${encodeURIComponent(paramsStr)}`,
      })
    }
    // const paramsStr = JSON.stringify({"cinemaName":"中影万泰LUXE巨幕影城（石岩创维店）","cinemaId":"124801","hall":"4号厅","movieName":"刀尖","movieImg":"https://gw.alicdn.com/i2/O1CN01qp0IQD1SmPUNTpYeU_!!6000000002289-0-alipicbeacon.jpg_480x480Q30s150.jpg","movieId":"2537","grade":"7.5","duration":121,"time":"今天11月24日 17:10:0","price":"44.00","seat":[{"seatId":"MTI0ODAxQF9AMjUzN0BfQDE3MDA4MTcwMDBAX0A3QF9AMzZAX0AwMDAwMDAzMzg3MS02LTEwQF9AODhAX0AwQF9ANuaOkjbluqdAX0AxMjM0MTM4M0BfQDA=","seatInfo":"6排6座","columnNo":"9","rowNo":"6","index":"96"}],"loveStatus":"0","seatIds":["MTI0ODAxQF9AMjUzN0BfQDE3MDA4MTcwMDBAX0A3QF9AMzZAX0AwMDAwMDAzMzg3MS02LTEwQF9AODhAX0AwQF9ANuaOkjbluqdAX0AxMjM0MTM4M0BfQDA="],"seatNo":["6排6座"],"showId":"47578556ba2c92410007","ticketNum":1,"ticketOriginalPrice":"44.90","ticketUnitPrice":"44.00"});
    
  },
  // 报价和改价
  checkoutStatus(e){
    const _this = this;
    const { name, index } = e.target.dataset
    let data = this.data[name];
    console.log(name, index);
    if(!data[index].bidPrice) {
      return wx.showToast({
        icon: 'none',
        title: '请输入报价',
      })
    }
    const url = this.data.currentTab == 0 ? '/appletSupplierRob/orderQuote' : '/appletSupplierRob/changeQuote'
    wx.request({
      url: app.globalData.url + url,
      method: 'POST',
      header:{
        consumerId: app.globalData.userInfo.consumerId
      },
      data: {
        orderNo: data[index].orderNo,
        orderQuote: data[index].bidPrice
      },
      success: function (res) {
        if(res.data.code == 200) {
          if(_this.data.currentTab == 0 ) {
            _this.initGet(0)
          } else {
            _this.initGet(1)
          }
          wx.showToast({
            icon: 'none',
            title: '报价成功',
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
          })
        }
      }
    })
   
  },
  // 取消报价
  closeStatus(e) {
    const _this = this;
    const { name, index } = e.target.dataset
    let data = this.data[name];
    wx.request({
      url: app.globalData.url + '/appletSupplierRob/refundOrder',
      method: 'POST',
      header:{
        consumerId: app.globalData.userInfo.consumerId
      },
      data: {
        orderNo: data[index].orderNo,
      },
      success: function (res) {
        if(res.data.code == 200) {
          _this.setData({
            items1: [], //全部订单
            pageNum1: 0,
            has1: true,
            loading1: false,
          })
          _this.get1();
          wx.showToast({
            icon: 'none',
            title: '取消订单成功',
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
          })
        }
      }
    })
  },
  // 输入报价和改价双向绑定
  bindinput(e) {
    const val = e.detail.value;
    const { name, index } = e.target.dataset
    const items = this.data[name];
    items[index].bidPrice = val
    this.setData({
      [name]: items
    })
  },
  initGet(current){
    if (current == 0) {
      this.setData({
        items0: [], //全部订单
        pageNum0: 0,
        has0: true,
        loading0: false,
      },()=> {
        this.get0();
      })
    } else if (current == 1) {
    this.setData({
      items1: [], // 完成订单
      pageNum1: 0,
      has1: true,
      loading1: false,
    }, ()=> {
      this.get1();
    })
  } else if (current == 2) {
      this.setData({
        items2: [], // 失效订单
        pageNum2: 0,  
        has2: true,
        loading2: false,
      }, ()=> {
        this.get2();
      })
    }
  }
})